package com.xy.exam.config;

import com.xy.exam.utils.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * JWT认证过滤器 - 简化版
 * 集成Redis缓存验证
 */
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtUtil jwtUtil;
    private final UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain
    ) throws ServletException, IOException {
        final String authHeader = request.getHeader("Authorization");
        
        // 如果没有认证头或不是Bearer令牌，则放行请求
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }
        
        try {
            // 提取JWT令牌
            final String jwt = authHeader.substring(7);
            // 提取用户名
            final String username = jwtUtil.extractUsername(jwt);
            
            // 如果提取到用户名并且当前未认证
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                // 从用户详情服务获取用户详情
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                
                // 使用Redis验证令牌
                if (jwtUtil.validateToken(username, jwt)) {
                    // 创建认证令牌
                    UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
                            userDetails,
                            null,
                            userDetails.getAuthorities()
                    );
                    
                    // 设置认证详情
                    authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    
                    // 更新安全上下文
                    SecurityContextHolder.getContext().setAuthentication(authToken);
                }
            }
        } catch (Exception e) {
            // 异常处理 - 简单记录而不中断
            logger.error("无法验证JWT令牌", e);
        }
        
        // 继续处理请求
        filterChain.doFilter(request, response);
    }
} 